package com.company.cloud.behavior.modules.app.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.company.cloud.behavior.modules.api.response.BehaviorSearchParam;
import com.company.cloud.behavior.modules.api.response.CommentModel;
import com.company.cloud.behavior.modules.api.service.BehaviorClientService;
import com.company.cloud.behavior.modules.app.controller.req.CommentQueryByObjParam;
import com.company.cloud.behavior.modules.app.controller.req.CommentSaveParam;
import com.company.cloud.behavior.modules.base.entity.UserCommentInfo;
import com.company.cloud.behavior.modules.base.service.UserCommentInfoService;
import com.company.cloud.behavior.modules.cache.service.BehaviorCacheService;
import com.company.cloud.behavior.modules.cache.utils.BehaviorConvertUtils;
import com.company.cloud.common.asserts.ValidatorUtils;
import com.company.cloud.common.auth.annotation.Login;
import com.company.cloud.common.bean.BaseClientResult;
import com.company.cloud.common.bean.BaseResult;
import com.company.cloud.common.bean.LoginSimpleUserInfo;
import com.company.cloud.common.constant.BaseConstant.EnabledEnum;
import com.company.cloud.common.constant.BaseReturnEnum;
import com.company.cloud.common.exception.BusinessException;
import com.company.cloud.common.utils.AuthContextUtils;
import com.company.cloud.common.utils.StrSplitUtils;
import com.company.cloud.company.modules.api.request.ThirdPlatformValidateContentRequest;
import com.company.cloud.company.modules.api.response.ValidateContentResp;
import com.company.cloud.company.modules.api.service.CompanyConfigRemoteService;
import com.company.cloud.user.modules.api.response.UserSimple;
import com.company.cloud.user.modules.api.service.UserRemoteService;
import com.company.common.server.constant.IRelBusiType;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.*;

/**
 * 评论信息
 */
@RestController
@RequestMapping("/common/comment")
@Api(tags = "App_common_评论信息")
public class CommentController {

    @Autowired
    private UserCommentInfoService userCommentInfoService;

    @Autowired
    private UserRemoteService userRemoteService;

    @Autowired
    private BehaviorCacheService behaviorCacheService;

    @Qualifier("behaviorClientServiceImpl")
    @Autowired
    private BehaviorClientService behaviorClientService;

    @Autowired
    private CompanyConfigRemoteService companyConfigRemoteService;

    @PostMapping("/query")
    @ApiOperation(value = "根据评论对象获取评论列表", response = CommentModel.class)
    public BaseResult query(@RequestBody CommentQueryByObjParam params) {
        ValidatorUtils.validate(params);
        IPage<UserCommentInfo> page = userCommentInfoService.page(new Page<UserCommentInfo>(params.getPage(), params.getRows()),
                new QueryWrapper<UserCommentInfo>()
                        .eq("obj_type", params.getObjType())
                        .eq("obj_no", params.getObjNo())
                        .eq("parent_id", 0)
                        .orderByDesc("comment_time")
        );
        if (page == null || CollectionUtils.isEmpty(page.getRecords())) {
            return BaseResult.ok();
        }
        Set<Integer> userIds = new HashSet<Integer>();
        Set<Integer> ids = new HashSet<Integer>();
        page.getRecords().forEach(item -> {
            ids.add(item.getId());
            userIds.add(item.getUserId());
        });

        List<UserCommentInfo> childList = userCommentInfoService.list(
                new QueryWrapper<UserCommentInfo>().in("main_id", ids));
        if (!CollectionUtils.isEmpty(childList)) {
            childList.forEach(item -> {
                userIds.add(item.getUserId());
            });
        }

        BaseClientResult<Map<Integer, UserSimple>> userMap = userRemoteService.getUserMapByIds(userIds);
        LoginSimpleUserInfo loginSimpleUserInfo = AuthContextUtils.getUserNoValidate();
        BehaviorSearchParam pa = new BehaviorSearchParam();
        if (loginSimpleUserInfo != null) {
            pa.setUserId(loginSimpleUserInfo.getId());
        }
        pa.setObjType(IRelBusiType.BASIC_Comment);
        IPage<CommentModel> data = page.convert(entity -> {
            CommentModel model = BehaviorConvertUtils.getCommentModel(entity, userMap.getData());
            pa.setObjNo(Integer.toString(model.getId()));
            // 获取评论的点赞信息
            model.setThumbsUpSearchModel(behaviorClientService.getThumbsUpInfo(pa).getData());
            return model;
        });

        if (!CollectionUtils.isEmpty(childList)) {
            List<CommentModel> commentModelList = new ArrayList<CommentModel>();
            childList.forEach(item -> {
                commentModelList.add(BehaviorConvertUtils.getCommentModel(item, userMap.getData()));
            });
            for (CommentModel item : data.getRecords()) {
                item.setChildren(this.getChildren(commentModelList, item.getId()));
            }
        }


        return BaseResult.ok(data);
    }


    private List<CommentModel> getChildren(List<CommentModel> data, int parendId) {
        List<CommentModel> returnList = new ArrayList<CommentModel>();
        for (CommentModel model : data) {
            if (model.getParentId() == parendId) {
                model.setChildren(this.getChildren(data, model.getId()));
                returnList.add(model);
            }
        }
        return returnList;
    }


    @GetMapping("/get")
    @ApiOperation(value = "评论详细信息")
    public BaseResult get(@RequestParam("id") Integer id) {
        UserCommentInfo entity = userCommentInfoService.getById(id);
        if (entity == null || entity.getParentId() <= 0) {
            throw new BusinessException(BaseReturnEnum.DATA_NOT_EXISTS);
        }
        List<UserCommentInfo> childList = userCommentInfoService.list(new QueryWrapper<UserCommentInfo>()
                .eq("obj_type", entity.getObjType())
                .eq("obj_no", entity.getObjNo())
                .like("tree_path", StrUtil.format(",{},", entity.getId().toString()))
                .eq("rows_state", EnabledEnum.ENABLED.getCode())
        );

        Set<Integer> userIds = new HashSet<Integer>();
        userIds.add(entity.getUserId());
        if (!CollectionUtils.isEmpty(childList)) {
            childList.forEach(item -> {
                userIds.add(item.getUserId());
            });
        }
        BaseClientResult<Map<Integer, UserSimple>> userMap = userRemoteService.getUserMapByIds(userIds);

        CommentModel data = BehaviorConvertUtils.getCommentModel(entity, userMap.getData());

        if (!CollectionUtils.isEmpty(childList)) {
            List<CommentModel> commentModelList = new ArrayList<CommentModel>();
            childList.forEach(item -> {
                commentModelList.add(BehaviorConvertUtils.getCommentModel(item, userMap.getData()));
            });
            data.setChildren(this.getChildren(commentModelList, data.getId()));
        }
        return BaseResult.ok(data);
    }

    @Login
    @GetMapping("/delete")
    @ApiOperation(value = "评论信息删除")
    public BaseResult delete(@RequestParam("id") Integer id) {
        UserCommentInfo entity = userCommentInfoService.getById(id);
        if (null == entity) {
            throw new BusinessException(BaseReturnEnum.DATA_NOT_EXISTS);
        }
        userCommentInfoService.remove(new QueryWrapper<UserCommentInfo>().like("tree_path", StrUtil.format(",{},", id.toString())));
        userCommentInfoService.removeById(id);
        behaviorCacheService.updateCommentCount(entity.getObjType(), entity.getObjNo(), -1);
        return BaseResult.ok();
    }

    @Login
    @PostMapping("/save")
    @ApiOperation(value = "评论信息表新增")
    public BaseResult save(@RequestBody CommentSaveParam params) {
        ValidatorUtils.validate(params);

        if (StrUtil.isNotEmpty(params.getContent())) {
            BaseClientResult<ValidateContentResp> result = companyConfigRemoteService.validateContent(new ThirdPlatformValidateContentRequest(params.getContent()));
            ValidateContentResp vcr = BaseClientResult.getResultData(result);
            if (vcr == null || vcr.getCode() != 0) {
                throw new BusinessException(BaseReturnEnum.PARAM_ERROR.getCode(), "非法内容");
            }
        }


        UserCommentInfo parentComment = null;
        if (params.getParentId() != null) {
            parentComment = userCommentInfoService.getById(params.getParentId());
        }

        if (parentComment == null) {
            if (StringUtils.isEmpty(params.getObjType()) || StringUtils.isEmpty(params.getObjNo())) {
                throw new BusinessException(BaseReturnEnum.PARAM_ERROR);
            }
        }

        LoginSimpleUserInfo userInfo = AuthContextUtils.getUser();

        UserCommentInfo entity = new UserCommentInfo();
        entity.setCompanyNo(userInfo.getCompanyNo());
        entity.setUserId(userInfo.getId());
        entity.setContent(params.getContent());
        entity.setImage(StrSplitUtils.list2string(params.getImage()));
        entity.setCommentTime(LocalDateTime.now());

        if (parentComment == null) {
            entity.setObjType(params.getObjType());
            entity.setObjNo(params.getObjNo());
            entity.setParentId(0);
            entity.setMainId(0);
            entity.setTreePath(",");
        } else {
            entity.setObjType(parentComment.getObjType());
            entity.setObjNo(parentComment.getObjNo());
            entity.setParentId(params.getParentId());
            entity.setMainId(parentComment.getMainId().intValue() == 0 ? parentComment.getId() : parentComment.getMainId());
        }
        entity.addCreateParam(userInfo);
        entity.addEditParam(userInfo);
        userCommentInfoService.save(entity);

        if (parentComment != null) {
            entity.setTreePath(parentComment.getTreePath() + entity.getId().toString() + ",");
            userCommentInfoService.updateById(entity);
        } else {
            entity.setTreePath("," + entity.getId().toString() + ",");
            userCommentInfoService.updateById(entity);
        }
        behaviorCacheService.updateCommentCount(entity.getObjType(), entity.getObjNo(), 1);
        return BaseResult.ok();
    }

}
